import os
from datetime import datetime


class WriteLog:
    def __init__(self):
        pass

    @staticmethod
    def get_file_size(f_path):
        fsize = os.path.getsize(f_path)
        # 换算成MB
        fsize = fsize / float(1024 * 1024)

        return fsize

    def write_file_with_part(self, f_path, file_num, text):
        os.makedirs(os.path.dirname(f_path), exist_ok=True)
        if os.path.exists(f_path):
            file_size = self.get_file_size(f_path)
            if file_size >= 10:
                new_name = str(os.path.basename(f_path).split('.')[0]) \
                           + f'_{file_num}' \
                           + os.path.splitext(f_path)[-1]
                f_path = os.path.join(os.path.dirname(f_path),
                                      new_name)
                file_num += 1
        if file_num == 1:
            mode = 'w'
        else:
            mode = 'a'
        with open(f_path, mode, encoding='utf-8', errors='ignore') as f:
            now_time = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
            f.write(f'[{now_time}] {text}\n')
        return file_num

    @staticmethod
    def write_file(f_path, text):
        os.makedirs(os.path.dirname(f_path), exist_ok=True)
        with open(f_path, 'a', encoding='utf-8', errors='ignore') as f:
            now_time = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
            f.write(f'[{now_time}] {text}\n')

    @staticmethod
    def print_log(text):
        now_time = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
        print(f'[{now_time}] {text}\n')

    @staticmethod
    def print_error(text):
        now_time = datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')
        print(f"\033[31m[{now_time}] {text}\033[0m")
